<template>
    <div class="layout-route">
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <el-form-item label="订单号" prop="order_id">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_id" placeholder="请输入订单号" clearable />
                </el-form-item>
                <el-form-item label="订单编号" prop="order_number">
                    <el-input type="textarea" :rows="4" v-model="queryParams.order_number" placeholder="请输入订单编号" clearable size="small" style="width: 240px" />
                </el-form-item>
                <el-form-item label="店铺" prop="shop_id">
                    <el-select v-model="queryParams.shop_id" placeholder="请选择店铺" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in shopList" :key="index" :label="dict.shop_name" :value="dict.shop_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="SKU" prop="sku">
                    <el-input v-model.trim="queryParams.sku" placeholder="请输入SKU" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="拆单结果" prop="split_status">
                    <el-select v-model="queryParams.split_status" placeholder="全部" clearable>
                    <el-option v-for="item in STATUS_LIST" :label="item.label" :value="item.value" :key="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间" prop="create_time">
                    <el-date-picker
                        v-model="queryParams.create_time"
                        type="daterange"
                        range-separator="至"
                        @change="handleDateRangeChange"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width: 240px"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" size="large" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="large" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download"  :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="el-icon-plus" @click="markAsProcessed">标记成已处理</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-tabs v-model="queryParams.send_status" type="border-card" @tab-click="handleQuery">
                <el-tab-pane label="全部" :name="undefined"></el-tab-pane>
                <el-tab-pane v-for="item in SEND_STATUS_LIST" :key="item.value" :label="item.label" :name="item.value.toString()"></el-tab-pane>
            </el-tabs>
            <div class="table-wrap">
                <el-table v-loading="loading" :data="tableData" border script @selection-change="handleSelectionChange" ref="multipleTable"  >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="ID" prop="id" min-width="55"></el-table-column>
                    <el-table-column label="订单ID" prop="order_id" min-width="120" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <el-link :underline="false" type="primary" @click="showDetailDialog(scope.row)">{{ scope.row.order_id }}</el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单编号" prop="order_number" min-width="120" show-overflow-tooltip></el-table-column>
                    <el-table-column label="店铺" prop="shop_name" min-width="120" show-overflow-tooltip></el-table-column>
                    <el-table-column label="SKU" prop="sku" min-width="200" show-overflow-tooltip></el-table-column>
                    <el-table-column label="数量" prop="num" min-width="100"></el-table-column>
                    <el-table-column label="拆单结果" prop="split_status" min-width="120" show-overflow-tooltip>
                        <template slot-scope="scope">
                            {{ scope.row.split_status  | formatLabelByValueFuzzy(STATUS_LIST)}}
                        </template>
                    </el-table-column>
                    <el-table-column label="失败原因" prop="split_res" min-width="200" show-overflow-tooltip></el-table-column>
                    <el-table-column label="创建时间" prop="create_time" min-width="160"></el-table-column>
                    <el-table-column label="操作" fixed="right" min-width="100">
                        <template slot-scope="scope">
                            <!-- <el-button el-button type="text" icon="el-icon-search" @click="showDetailDialog(scope.row)">查看详情</el-button> -->
                            <el-button v-show="scope.row.send_status == 1 && scope.row.split_status == 2" type="text" icon="el-icon-refresh" @click="refreshRow(scope.row)">重试</el-button> 
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList"></pagination>
        </div>
        <detail-dialog v-model="detailDialog.visible" v-if="detailDialog.visible" :params="detailDialog.data" @success="handleQuery"></detail-dialog>
    </div>
</template>

<script>
import { getOrderSplitList, export_explode_info, updateOrderSplitChange, splitOrder } from '@/api/order'
import { getShopList } from '@/api/shop'
import { STATUS_LIST, SEND_STATUS_LIST } from './constant'
import DetailDialog from './components/DetailDialog.vue'
import { exportFile } from '@/utils/index'

export default {
    name: 'OrderList',
    components: { DetailDialog },
    data() {
        return {
            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            STATUS_LIST,
            SEND_STATUS_LIST,
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                order_id: undefined,
                order_number: undefined,
                shop_id: undefined,
                sku: undefined,
                split_status: undefined,
                create_time: [],
            },
            detailDialog: {
                visible: false,
                data: {},
            },
            shopList: [],
            multipleSelection: []
        }
    },
    async created() {
        this.loading = true
        try {
            const result = await getShopList()
            this.shopList = result?.data?.list ?? []
        } catch (error) {
            console.log(error)
            this.loading = false
        }
        this.getList()
    },
    methods: {
        refreshRow(row) {
            splitOrder({ order_id: row.order_id, shop_id: row.shop_id })
                .then(res => {
                    this.$message.success('操作成功')
                    this.getList()
                })
                .catch(err => {
                    this.$message.error(err.message)
                })
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            export_explode_info(qyparams)
                .then(res => {
                    console.log(res)
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        handleSelectionChange(val) {  
            this.multipleSelection = val.map(item => item.id)
        }, 
        markAsProcessed() {
            if(this.multipleSelection?.length == 0){
                return this.msgError('请勾选再操作')
            }
            this.$confirm(`是否确认修改为已处理?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.loading = true
                    updateOrderSplitChange({ids: this.multipleSelection}).then(res => {
                        this.$message.success('操作成功')
                        this.getList()
                    }).catch(err => {
                        this.$message.error(err.message)
                    }).finally(() => {
                        this.loading = false
                    })
                })
                .catch(() => {})
        },
        handleDateRangeChange(value) {
            this.queryParams.create_time = value.map(dateStr => {
                const date = new Date(dateStr)
                const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(
                    2,
                    '0',
                )}:${String(date.getMinutes()).padStart(2, '0')}`
                return formattedDate
            })
        },
        showDetailDialog(row) {
            if(row.split_status == 2) {
                this.$message.error('该订单拆分失败，不能查看详情')
                return
            }
            this.detailDialog.visible = true
            this.detailDialog.data = row
        },
        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            getOrderSplitList(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },
    },
}
</script>
<style scoped>
.el-tabs--border-card {
    box-shadow: none;
    border-bottom: 0;
}

::v-deep .el-tabs .el-tabs__content {
    padding: 0;
    border-bottom: 0;
}
.table-wrap {
    padding: 15px;
    border-bottom: 1px solid #dfe4ed;
    border-left: 1px solid #dfe4ed;
    border-right: 1px solid #dfe4ed;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
</style>